package com.foreveross.weixin.util;

import java.net.URLEncoder;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.util.JSONUtil;
import com.foreveross.weixin.common.Constant;
import com.foreveross.weixin.vo.AccessToken;
import com.foreveross.weixin.vo.JsApiTicket;
import com.foreveross.weixin.vo.ResultVo;
import com.foreveross.weixin.vo.UserInfo;
import com.foreveross.weixin.vo.Qrcode.ActionName;
import com.foreveross.weixin.vo.Qrcode.QrcodeTicket;
import com.foreveross.weixin.vo.Qrcode.QrcodeTicketScene;
import com.foreveross.weixin.vo.Qrcode.QrcodeTicketSceneVo;
import com.foreveross.weixin.vo.Qrcode.QrcodeTicketVo;
import com.foreveross.weixin.vo.pay.PayOrderQueryResult;
import com.foreveross.weixin.vo.pay.PayRefundResult;
import com.foreveross.weixin.vo.pay.PayUnifiedOrderResult;
import com.foreveross.weixin.vo.pojo.Menu;

public class WeixinUtil {
	private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);  
    
    /** 
     * 获取access_token 
     *  
     * @param appid 凭证 
     * @param appsecret 密钥 
     * @return 
     */  
    public static AccessToken getAccessToken(String appid, String appsecret) {  
        AccessToken accessToken = null;  
      
        String requestUrl = Constant.access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);  
        String str = HttpUtil.get(requestUrl);
        // 如果请求成功  
        if (null != str) {  
            accessToken = StringUtil.StrToClazz(str, AccessToken.class);
        }  
        return accessToken;  
    } 
    
    
    /** 
     * 获取JsApiTicket 
     *  
     * @param accessToken 
     * @return JsApiTicket
     */  
    public static JsApiTicket getJsApiTicket(String accessToken) {  
    	JsApiTicket jsApiTicket = null;  
      
        String requestUrl = Constant.jsapi_tickect.replace("ACCESS_TOKEN", accessToken);  
        String str = HttpUtil.get(requestUrl);
        // 如果请求成功  
        if (null != str) {  
        	jsApiTicket = StringUtil.StrToClazz(str, JsApiTicket.class);
        }  
        return jsApiTicket;  
    } 
    
    /**
     * 用户同意授权，获取code
     * @param appid
     * @param redirectUrl
     * @param state
     */
    public static String validateOauth2AuthorizeCode(String appid, String redirectUrl,boolean isBase,String state) {  
        String requestUrl = null;
        if(isBase){
        	requestUrl = Constant.oauth2_authorize_code_url.replace("APPID", appid)
					.replace("REDIRECT_URI", URLEncoder.encode(redirectUrl))
					.replace("SCOPE", Constant.SCOPE_SNSAPI_BASE)
					.replace("STATE", state); 
        }else{
        	requestUrl = Constant.oauth2_authorize_code_url.replace("APPID", appid)
					.replace("REDIRECT_URI", URLEncoder.encode(redirectUrl))
					.replace("SCOPE", Constant.SCOPE_SNSAPI_USERINFO)
					.replace("STATE", state); 
        }
        		 
        System.out.println("WeixinUtil validateOauth2AuthorizeCode:"+requestUrl);
        return requestUrl;
    } 
    
    /** 
     * 获取 Oauth2 access_token 
     *  
     * @param appid 凭证 
     * @param appsecret 密钥 
     * @return 
     */  
    public static AccessToken getOauth2AccessToken(String appid, String appsecret,String code) {  
        AccessToken accessToken = null;  
      
        String requestUrl = Constant.oauth2_access_token_url.replace("APPID", appid)
        											.replace("SECRET", appsecret)
        											.replace("CODE", code);  
        System.out.println("WeixinUtil getOauth2AccessToken"+requestUrl);
        String str = HttpUtil.get(requestUrl);
        // 如果请求成功  
        if (null != str) { 
        	try{
        		accessToken = StringUtil.StrToClazz(str, AccessToken.class);
        	}catch(Exception e){
        		System.out.println(str);
        	}
        }  
        System.out.println("WeixinUtil getOauth2AccessToken:"+str);
        System.out.println("WeixinUtil getOauth2AccessToken Access_token:"+accessToken.getAccess_token());
        return accessToken;  
    } 
    
    public static AccessToken refreshOauth2AccessToken(String appid,String refreshToken) {  
        AccessToken accessToken = null;  
      
        String requestUrl = Constant.oauth2_refresh_token_url.replace("APPID", appid)
        											.replace("REFRESH_TOKEN", refreshToken);  
        String str = HttpUtil.get(requestUrl);
        // 如果请求成功  
        if (null != str) { 
        	try{
        		accessToken = StringUtil.StrToClazz(str, AccessToken.class);
        	}catch(Exception e){
        		System.out.println(str);
        	}
        } 
        System.out.println("WeixinUtil refreshOauth2AccessToken:"+str);
        return accessToken;  
    } 
    
    
    public static UserInfo getOauth2UserInfo(String access_token,String openid) {  
    	UserInfo userInfo = null;  
      
        String requestUrl = Constant.oauth2_userinfo_url.replace("ACCESS_TOKEN", access_token)
        											.replace("OPENID", openid);  
        String str = HttpUtil.get(requestUrl);
        // 如果请求成功  
        if (null != str) { 
        	try{
        		userInfo = StringUtil.StrToClazz(str, UserInfo.class);
        	}catch(Exception e){
        		System.out.println(str);
        	}
        }   
        return userInfo;  
    }
    
    
    public static boolean validateAccessToken(String access_token,String openid) {  
    	ResultVo resultVo = null;  
    	boolean isTrue = true;
        String requestUrl = Constant.oauth2_check_access_token_url.replace("ACCESS_TOKEN", access_token)
        											.replace("OPENID", openid);  
        String str = HttpUtil.get(requestUrl);
        // 如果请求成功  
        if (null != str) {  
        	System.out.println(str);
        	resultVo = StringUtil.StrToClazz(str, ResultVo.class);
        	if(resultVo.getErrcode() == 0) isTrue = true;
        	else isTrue = false;
        }  
        return isTrue;  
    }
    
    public static String getMedia(String access_token,String media_id,String basePath,String uploadPath){
    	System.out.println("WeixinUtil getMedia:"+access_token);
    	String requestUrl = Constant.get_media_url.replace("ACCESS_TOKEN", access_token)
					.replace("MEDIA_ID", media_id);  
    	String str = null;
    	str = HttpUtil.get(requestUrl, basePath, uploadPath, media_id);
    	return str;
    }
    
    public static QrcodeTicket getQrcodeTicket(String access_token,String jsonStr){
    	System.out.println("WeixinUtil getQrcodeTicket:"+access_token);
    	String requestUrl = Constant.get_qrcode_ticket_url.replace("TOKEN", access_token);  
    	String str = HttpUtil.Post(requestUrl, jsonStr,"application/json","UTF-8");
    	System.out.println("===================================================================================================");
    	System.out.println("-----------------------QrcodeTicket getQrcodeTicket------------------------------------------"+str);
        // 如果请求成功  
    	QrcodeTicket qrcodeTicket = null;
        if (null != str) { 
        	try{
        		qrcodeTicket = StringUtil.StrToClazz(str, QrcodeTicket.class);
        	}catch(Exception e){
        		System.out.println(str);
        	}
        }  
    	return qrcodeTicket;
    }
    
    /**
     * 统一下单
     * @param xmlStr
     * @return
     */
    public static PayUnifiedOrderResult getPayUnifiedOrderResult(String xmlStr){
    	String requestUrl = Constant.pay_unifiedorder_url;  
    	
    	String str = HttpUtil.Post(requestUrl, xmlStr,null,null);
    	System.out.println(str);
        // 如果请求成功  
    	PayUnifiedOrderResult payUnifiedOrderResult = null;
        if (null != str) { 
        	try{
        		Map<String,String> map = XmlUtil.parseXml(str);
        		
        		payUnifiedOrderResult = StringUtil.MapToClazz(map, PayUnifiedOrderResult.class);
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        }  
    	return payUnifiedOrderResult;
    }
    
    /**
     * 查询订单
     * @param xmlStr
     * @return
     */
    public static PayOrderQueryResult getPayOrderQueryResult(String xmlStr){
    	String requestUrl = Constant.pay_orderquery_url;  
    	
    	String str = HttpUtil.Post(requestUrl, xmlStr,null,null);
    	System.out.println(str);
        // 如果请求成功  
    	PayOrderQueryResult payOrderQueryResult = null;
        if (null != str) { 
        	try{
        		Map<String,String> map = XmlUtil.parseXml(str);
        		
        		payOrderQueryResult = StringUtil.MapToClazz(map, PayOrderQueryResult.class);
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        }  
    	return payOrderQueryResult;
    }
    
    /**
     * 申请退款
     * @param xmlStr
     * @return
     */
    public static PayRefundResult getPayRefundResult(String xmlStr,String certUrl, String certPasse){
    	String requestUrl = Constant.pay_refund_url;  
    	
    	String str = HttpUtil.PostSSL(requestUrl, xmlStr,certUrl,certPasse);
    	System.out.println(str);
        // 如果请求成功  
    	PayRefundResult payRefundResult = null;
        if (null != str) { 
        	try{
        		Map<String,String> map = XmlUtil.parseXml(str);
        		
        		payRefundResult = StringUtil.MapToClazz(map, PayRefundResult.class);
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        }  
    	return payRefundResult;
    }
    
    
    /** 
     * 创建菜单 
     *  
     * @param menu 菜单实例 
     * @param accessToken 有效的access_token 
     * @return 0表示成功，其他值表示失败 
     */  
    public static int createMenu(Menu menu, String accessToken) {  
        int result = 0;  
        // 拼装创建菜单的url  
        String url = Constant.menu_create_url.replace("ACCESS_TOKEN", accessToken);  
        // 将菜单对象转换成json字符串  
        String jsonMenu = StringUtil.ClazzToJsonStr(menu);
        System.out.println(jsonMenu);
        String content =  HttpUtil.Post(url, jsonMenu,"application/json","UTF-8");
        // 调用接口创建菜单  
        ResultVo resultVo = StringUtil.StrToClazz(content, ResultVo.class);
        if (null != resultVo) {  
            if (0 != resultVo.getErrcode()) {  
                result = resultVo.getErrcode();
                log.error("创建菜单失败 errcode:{} errmsg:{}", resultVo.getErrcode(), resultVo.getErrmsg());  
            }  
        }  
        
        return result;  
    }  
    
    
    public static void main(String[] args) {
    	String a = validateOauth2AuthorizeCode(Constant.appId, "http://crcszwy.com/HRTenement/",true, "");
    	String b = HttpUtil.get(a);
    	System.out.println(b);
    /*	AccessToken  accessToken  =getAccessToken(Constant.appId, Constant.appSecret);
    	QrcodeTicketVo qrcodeTicketVo = new QrcodeTicketVo();
    	qrcodeTicketVo.setExpire_seconds(7200);
    	qrcodeTicketVo.setAction_name(ActionName.QR_SCENE.getValue());
    	QrcodeTicketScene qrcodeTicketScene = new QrcodeTicketScene();
    	QrcodeTicketSceneVo qrcodeTicketSceneVo = new QrcodeTicketSceneVo();
    	UserInfo s = new UserInfo();
    	s.setCity("123");
    	s.setSex("男");
    	qrcodeTicketSceneVo.setObj(s);
    	qrcodeTicketSceneVo.setScene_id(123);
    	qrcodeTicketScene.setScene(qrcodeTicketSceneVo);
    	qrcodeTicketVo.setAction_info(qrcodeTicketScene);
    	String jsonStr = JSONUtil.toJsonWithGson(qrcodeTicketVo);
    	QrcodeTicket a = getQrcodeTicket(accessToken.getAccess_token(), jsonStr);
    	System.out.println(a.getUrl());
    	System.out.println(a.getTicket());*/
    	
    	//System.out.println(URLEncoder.encode(a.getTicket()));
    	
	}
}
